package com.myNovel.novel.core.config;

import com.github.benmanes.caffeine.cache.Caffeine;
import com.myNovel.novel.core.common.constant.CacheConstants;
import org.apache.el.parser.SimpleCharStream;
import org.springframework.cache.CacheManager;
import org.springframework.cache.caffeine.CaffeineCache;
import org.springframework.cache.support.SimpleCacheManager;
import org.springframework.context.annotation.Bean;

import javax.swing.text.StyleConstants;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @Author：Guxx
 * @Package：com.myNovel.novel.core.config
 * @Date：2024/3/29 10:28
 * @Filename：CacheConfig
 */
public class CacheConfig {
    /**
     * caffeine 缓存管理
    * */
    @Bean
    public CacheManager caffeineCacheManager(){
        SimpleCacheManager cacheManager = new SimpleCacheManager();

        List<CaffeineCache> caches = new ArrayList<>(CacheConstants.CacheEnum.values().length);
       for (CacheConstants.CacheEnum c : CacheConstants.CacheEnum.values()){
           if(c.isLocal()){
               Caffeine<Object,Object> caffeine = Caffeine.newBuilder().recordStats().maximumSize(c.getMaxSize());

               if (c.getTtl() > 0){
                   caffeine.expireAfterWrite(Duration.ofSeconds(c.getTtl()));
               }
               caches.add(new CaffeineCache(c.getName(),caffeine.build()));
           }

       }
    cacheManager.setCaches(caches);

        return cacheManager;
    }
}
